#include <iostream>
#include <ctime>
#include <typeinfo>
#include "Agent.h"
#include "qdebug.h"
#include "TraceManager.h"

Agent::Agent(std::string name) {
	this->name = name;
	isBroken = false;
	messagesWillBeDisplayed = true;

	breakSemaphore = Sema(0);
}

void Agent::stateChanged()
{
	stateChangedSemaphore.post();
}

void Agent::msgToggleBreak()
{
	isBroken = !isBroken;
	// Un-break agent
	if (!isBroken)
	{
		breakSemaphore.post();
	}

	this->stateChanged(); 
}

void Agent::run()
{
	for (;;)
	{
		if (isBroken)
		{
			handleBreak();
			breakSemaphore.wait();
			handleFix();
		}
		stateChangedSemaphore.wait();
		while (pickAndExecuteAnAction()) ;
	}
}

void Agent::handleBreak()
{
}

void Agent::handleFix()
{
}

void Agent::setTracePanel(std::vector<std::string>* trace)
{
	this->tracePanel = trace;
}

void Agent::Do(std::string action)
{
	print(action); // pretend to perform an action
}

void Agent::print(std::string text)
{
	time_t currentTime = time(NULL);

	std::string toPrint = name + ": " + text;
	//if ( tracePanel != NULL )
	//{
	//this->tracePanel->push_back(toPrint);
	//}
	//else
	//{
	qDebug( toPrint.c_str() );
	//qDebug() << typeid(*this).name();
	//}
	//std::cout << name << ": " << text << std::endl;
	TraceManager::SharedManager()->addMessage(toPrint, currentTime, this);
}

std::string Agent::getName() const {
	return name;
}
